# 参考：https://stackoverflow.com/questions/16056793/python-win32com-client-dispatch-looping-through-word-documents-and-export-to-pdf
# 批量word转换器（单线程版，只有UI线程）
import os
import os.path
from win32com import client as wc
import PySimpleGUI as sg

def TransBatch(folder_name, window, out_format_number = 16, src_ext='.doc'):
    # 源格式和目标格式相同时，不执行转换
    if (src_ext=='.docx' and out_format_number==16) or (src_ext=='.doc' and out_format_number==0):
        window.write_event_value('-NOTHING-', '')
        return
    # Get all regular files
    names = [name for name in os.listdir(folder_name)
             if os.path.isfile(os.path.join(folder_name, name)) and name.endswith(src_ext)]
    word = wc.DispatchEx('Word.Application')
    total_cnt = len(names)
    for index, f_name in enumerate(names):
        # 获取旧doc格式word文件绝对路径名
        doc_full_path = os.path.join(folder_name, f_name)
        name_without_ext, ext = os.path.splitext(f_name)
        # 设置新文档文件名，不含扩展名。调用SaveAS时会自动添加扩展名
        docxName = os.path.join(folder_name, name_without_ext)

        # 打开 旧word 文件
        doc = word.Documents.Open(doc_full_path)
        # 保存为 新word 文件,其中参数 16 表示的是docx文件, 17表示pdf文件,0表示doc文件；调用SaveAS时会自动添加扩展名
        doc.SaveAs(docxName, out_format_number)
        # 关闭word文档
        doc.Close()
        print(f"{docxName} 生成完毕！")
        window['-OUT-'].update(f"第{index+1}/{total_cnt}个文件：{name_without_ext} 生成完毕！")
        window.refresh()
    word.Quit()
    window.write_event_value('-DONE-', '')

if __name__ == "__main__":
    # 原始文件的后缀（扩展名）
    src_dict ={'Radio_DOC':'.doc', 'Radio_DOCX': '.docx'}
    # 输出格式，必须使用代码表示, 参考：https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat
    format_dict = {'docx':16, 'pdf': 17, 'doc':0}

    src_ext = '.doc' #默认原始文件扩展名为.doc
    out_format_number = 16 #默认目标格式给docx，代码为16

    sg.theme('DefaultNoMoreNagging')

    layout = [[sg.Text('请输入文件夹名称（包含doc或docx文档）', font=('Helvetica', 11))],
              [sg.Input(key='-IN-'), sg.Button('Convert')],
              [sg.Text('原始格式：', font=('Helvetica', 9), justification='left'),
               sg.Radio('DOC', 'SRC', key='Radio_DOC', default=True, enable_events=True, size=(10, 1)),
               sg.Radio('DOCX', 'SRC', key='Radio_DOCX', enable_events=True, size=(10, 1))],
              [sg.Text('目标格式：', font=('Helvetica', 9), justification='left'),
               sg.Radio('TO DOCX', 'FORMAT', key='docx', default=True, enable_events=True, size=(10, 1)),
               sg.Radio('TO PDF', 'FORMAT', key='pdf', enable_events=True, size=(10, 1)),
               sg.Radio('TO DOC', 'FORMAT', key='doc', enable_events=True, size=(10, 1))
               ],
              [sg.Text(key='-OUT-')]
             ]

    window = sg.Window('word文件批量转换器', layout)
    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event in ['Radio_DOC','Radio_DOCX']:
            src_ext = src_dict[event]
        elif event in ['docx', 'pdf', 'doc']: #点击了Radio触发该事件
            out_format_number = format_dict[event]
        elif event == 'Convert':
            folder_path = values['-IN-']
            if len(folder_path) == 0:
                sg.popup('温馨提示', '请输入文件夹名称', values['-IN-'])
            else:
                TransBatch(folder_path, window, out_format_number, src_ext)
        elif event == '-DONE-':
            window['-OUT-'].update('转换完毕！')
            window.refresh()
        elif event=='-NOTHING-':
            # print(event)
            window['-OUT-'].update('目标格式和源格式相同，什么都不干！')
            window.refresh()
        # print(values)
    window.close()

